<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\common\logic\SmsLogic;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\model\mall\FreightTemplateModel;
use app\beautiful\model\mall\FreightTemplatePieceModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingIntegralModel;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\order\GoodsOrderModel;
use app\beautiful\model\setting\SettingSmsModel;
use think\facade\Db;
use app\beautiful\logic\LogsLogic;
use app\beautiful\logic\MemberWalletLogic;
class Order extends BaseController{
 
    
    //获取用户的订单信息
    public function getGoodsOrderList(){
        $status = $this->request->param('status/d');
        $where= [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0]
        ];
        switch ($status){ //查询订单的状态
            case 0: // 待付款
                $where[] = ['status','=',1];
                break;
            case 1: //待发货
                $where[] = ['status','=',2];
                break;
            case 2: //待收货
                $where[] = ['status','=',3];
                break;
            case 3://待自提
                $where[] = ['status','=',4];
                break;
            case 4://已完成  取消的订单也在已完成里面
                 $where[] = ['status','IN',[8,-1]];
                break;
        }
        $datas = GoodsOrderModel::with(['skus'])->where($where)
            ->field('order_id,order_type,logistics_type,total_price,is_paid,status,add_time')    
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->order(['order_id'=>'desc'])
            ->select()->append(['order_time','djs_time'])
            ->toArray();
        return $this->success([
            'list' => $datas
        ]);
    }
    
    
    //使用余额支付订单
    public function getGoodsOrderMoneyPay(){
        $order_id = $this->request->param('order_id/d');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if( null === $order = GoodsOrderModel::find($order_id)){
            return $this->error('订单不存在');
        }
        if($order->status != 1 || $order->is_delete == 1){
            return $this->error('订单不在未支付状态');
        }
        $time = time() - 900;//订单15分钟
        if($order->add_time < $time){ //如果 订单超过15分钟则不能支付了
            return $this->error('订单支付已经超时了，不能继续支付');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在'); 
        }
        Db::startTrans();
        try{
            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 12, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->use_integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->use_integral, 9);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->total_price * 100 + $order->freight * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }
            $res = $MemberWalletLogic->useBalance($needPay, $order->total_price + $order->freight , 8); //商城购物使用
            if($res == false){
                Db::rollback();
                return $this->error($MemberWalletLogic->getError());
            }
            $order->is_paid = 1;
            $order->pay_time = time();
            $order->status = $order->logistics_type == 1 ? 2 : 4; //订单的状态值
            $order->pay_type = 'money';
            $order->save();

            //发送短信给管理员
            try{
                $sms_setting = SettingSmsModel::where([['shop_id','=',$this->request->shopId]])->find();
                if(null !== $sms_setting){
                    if($sms_setting->order_notice_admin==1){
                        $sms_logic= new SmsLogic();
                        $params=[
                            'money'=>$needPay,
                        ];
                        $sms_logic->send($this->request->shopId,$sms_setting->boss_mobiles,$params,'orderNoticeAdmin');
                    }
                }
            }catch (\Exception $e){

            }

            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    
    
    
   
    //获取运费模版
    public function getFreightTemplate(){
         if(null === $freight_template = FreightTemplateModel::where('shop_id',$this->request->shopId)->find()){
             return $this->success(['freight_template'=>null]);
         }
         $piece = [];
         if($freight_template->freight_type==2){
            if(null === $freight_template_piece = FreightTemplatePieceModel::where('freight_template_id',$freight_template->freight_template_id)->find()){
                return  $this->success(['freight_template'=>null]);
            }
            $piece = [
                'base_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_num : '',
                'base_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->base_piece_price : '',
                'add_piece_num'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_num : '',
                'add_piece_price'=>isset($freight_template_piece) ? $freight_template_piece->add_piece_price : '',
                'piece_data'=>isset($freight_template_piece) ? $freight_template_piece->piece_data : [],
            ];
         }
        $detail=[
            'name'=>$freight_template->name,
            'hours'=>$freight_template->hours,
            'freight_type'=>$freight_template->freight_type,
            'valuation_type'=>$freight_template->valuation_type,
            'no_delivery_area'=>$freight_template->no_delivery_area,
            'piece' => $piece,
        ];
        return $this->success([
            'freight_template' => $detail
        ]);
    }
       
    public  function getGoodsOrderDetail(){
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $where= [
            ['shop_id','=', $this->request->shopId],
            ['member_id','=', $this->request->memberId],
            ['is_delete','=',0],
            ['order_id','=',$order_id]
        ];
        $datas = GoodsOrderModel::with(['skus'])->where($where)->find();
        if(null === $datas) return $this->error ('订单不存在');
        $datas->append(['order_time','djs_time','youhui','pay_time_format','pay_type_mean'])
            ->toArray(); 
        return $this->success([
            'detail' => $datas
        ]);
    }
    
    //确定收货
    public function yesOrder(){
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $order=GoodsOrderModel::find($order_id);
        if(null === $order) return $this->error ('订单不存在');
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        if($order->status != 3) return $this->error ('订单状态不正确');
        $order->status = 8;
        $order->save();
        return $this->success('确定成功');
    }
    public function deleteOrder(){ //只能删除 已完成的订单
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $order=GoodsOrderModel::find($order_id);
        if(null === $order) return $this->error ('订单不存在');
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('订单不存在');
        }
        if($order->status != 8 && $order->status != -1) return $this->error ('订单状态不正确');
        $order->is_delete = 1;
        $order->save();
        return $this->success('删除成功');
    }
    
    public function cancelOrder()
    {
        $order_id=$this->request->param('order_id/d',0);
        if(empty($order_id)) return $this->error('订单不存在');
        $params=[
            'member_id'=>$this->request->memberId,
            'order_id'=>$order_id,
        ];

        $order=GoodsOrderModel::find($order_id);
        if(null === $order) $this->error('订单不存在');
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_logic[$order->order_type]->cancelOrder($params);
            Db::commit();
            return $this->success('成功');
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    
}
